package main

import (
	"context"
	pb "demo/15/proto/model"
	"errors"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
	"net"
)

type UserService struct {
}

func (service *UserService) GetUserInfo(ctx context.Context, request *pb.UserRequest) (*pb.UserResponse, error) {
	fmt.Printf("try to get user info by %s", request.GetName())

	if len(request.GetName()) == 0 {
		return nil, errors.New("the query name cannot be empty")
	}

	// 通常逻辑是从数据库或者缓存中查询
	response := pb.UserResponse{Id: 123, Username: request.GetName(), Nickname: "尊敬的" + request.GetName()}

	return &response, nil
}

func main9() {
	// 监听127.0.0.1:8090
	ln, err := net.Listen("tcp", "127.0.0.1:8090")
	if err != nil {
		fmt.Println("建立监听出错")
		return
	}

	// 实例化grpc服务端
	server := grpc.NewServer()

	// 注册USER服务
	pb.RegisterUserServiceServer(server, &UserService{})

	// 往grpc服务端注册反射服务
	reflection.Register(server)

	// 启动grpc服务
	if err := server.Serve(ln); err != nil {
		fmt.Println("启动gRPC服务失败")
	}
}
